<?php
namespace app\api\controller;

use app\common\controller\Api;
use app\common\exception\UploadException;
use app\common\library\Ems;
use app\common\library\Sms;
use app\common\library\Upload;
use fast\Random;
use think\Config;
use think\Db;
use think\Validate;

/**
 * 示例接口
 */
class Icons extends Api
{


    // 无需登录的接口,*表示全部
    protected $noNeedLogin = [''];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];


    /* 所以的标签 */
    public function getallicons(){

        $list=Db::name('aa_icons')->select();

        foreach ($list as &$item){

            $item['image']=cdnurl($item['image'],true);
        }

        $this->success('所以的标签!', $list);
    }


    public function getalluser(){


        $list=Db::name('user')->where(['merch_id'=>0])->select();


        $this->success('选择用户!', $list);



    }

    /* 近期案例*/
    public function  getorder(){

        $list=Db::name('aa_case')
            ->limit(60)
            ->order('id desc')->select();


        $this->success('近期案例!', $list);

    }

    /* 提交信息 */
    public function submits(){

        $uid=$this->auth->id;

        $user=Db::name('user')->where(['id'=>$uid])->find();


        $data['msg']=$this->request->param('msg');
        $data['icon_id']=$this->request->param('icon_id');


        foreach ($data as $key=>$v){

            if (!$v){
                $this->error('请填写完整信息');
            }

        }

        $data['starttime']=strtotime($this->request->param('starttime'));
        $data['endtime']=strtotime($this->request->param('endtime'));
        $data['orders_id']=$this->request->param('orders_id');
        $data['userids']=trim($this->request->param('userid'),',');
        $data['user_id']=$uid;

        $titles='';
        $case=Db::name('aa_case')->where(['id'=>$data['orders_id']])->find();

        if  ($case){
            $data['merch_id']=$case['merch'];
            $titles=$case['title'];
        }else{


            $icon= Db::name('aa_icons')->where(['id'=>$data['icon_id']])->find();
            $titles=$icon['name'];
        }

        $data['user_id']=$uid;

        $data['images']=$this->request->param('images');
        $data['time']=time();

        $id=Db::name('aa_note')
            ->insertGetId($data);

        $this->sendmessagebygzh($data['userids'],$user['nickname'],$titles,date('y-m-d H:i',$data['starttime']),$id);


        $this->success('操作成功!');


    }

    public function sendmessagebygzh($userids,$one,$icon,$times,$id){

        $users=Db::name('user')->where('id','in',$userids)->select();


        

        foreach ($users as $key){


            if  ($key['merch_id']==0){
                $this->ajaxurl($key['unionid'],$one,$icon,$times,$id);
            }else{
                $this->ajaxurlb($key['unionid'],$one,$icon,$times,$id);

            }



        }


    }

    public function ajaxurl($mobile,$one,$icons,$times,$id){
        $ch = curl_init();

        $url = "http://gzh.stp1.cn/api/message/sendmsg";
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, 1);
        $postData = array(
            'mobile' => $mobile,
            'one'=>$one,
            'sku' => $icons,
            'times' => $times,
            'id' => $id
        );

        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $response = curl_exec($ch);

//        var_dump($response);

//        if (curl_errno($ch)) {
//            echo 'cURL Error: ' . curl_error($ch);
//        } else {
//            echo 'Response: ' . $response;
//        }

        curl_close($ch);


    }

    public function ajaxurlb($mobile,$one,$icons,$times,$id){
        $ch = curl_init();

        $url = "http://gzh.stp1.cn/api/message/sendmsgtouser";
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, 1);
        $postData = array(
            'mobile' => $mobile,
            'one'=>$one,
            'sku' => $icons,
            'times' => $times,
            'id' => $id
        );

        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $response = curl_exec($ch);

//        var_dump($response);

//        if (curl_errno($ch)) {
//            echo 'cURL Error: ' . curl_error($ch);
//        } else {
//            echo 'Response: ' . $response;
//        }

        curl_close($ch);


    }


      /**
     * 获取所有笔记信息
     *
     * @return void
     */
    public function getallnote()
    {
        // 获取请求参数
        $data = $this->request->param();

        // 初始化查询条件数组
        $map = [];

        // 处理订单 ID 条件
        if (!empty($data['order_id'])) {
            $map['aa_note.orders_id'] = $data['order_id'];
        }

        // 处理图标 ID 条件
        if (!empty($data['icons_id'])) {
            $map['aa_note.icon_id'] = $data['icons_id'];
        }

        // 处理商家 ID 条件
        if (!empty($data['merch_id'])) {
            if (is_numeric($data['merch_id'])) {
                $map['aa_note.merch_id'] = (int)$data['merch_id'];
            } else {
                $this->error('商家 ID 必须是数字类型');
                return;
            }
        }

        // 处理用户 ID 条件
        if (!empty($data['users_id'])) {
            $map['aa_note.user_id'] = $data['users_id'];
        }

        // 处理状态 ID 条件
        if (isset($data['status_id'])) {
            switch ($data['status_id']) {
                case 1:
                    $map['aa_note.status'] = 1;
                    break;
                case 0:
                    $map['aa_note.status'] = 0;
                    break;
                case 2:
                    $map['aa_note.status'] = [ '>', -1];
                    break;
                default:
                    $this->error('无效的状态 ID');
                    return;
            }
        }


            // 构建查询
            $query = Db::name('aa_note')
                ->alias('aa_note')
                ->join('aa_case ac', 'aa_note.orders_id = ac.id', 'LEFT')
                ->join('aa_icons ai', 'aa_note.icon_id = ai.id', 'LEFT')
                ->field([
                    'aa_note.*',
                    'ac.title as order_title',
                    'ai.name as icon_title',
                    'ai.image as icon_image'
                ])
                ->where($map)
                ->order('aa_note.id desc');

            // 执行查询
            $lists = $query->select();


            // 缓存用户信息和查看记录
            $userCache = [];
            $logCache = [];

            // 遍历结果集
            foreach ($lists as &$key) {
                // 格式化时间
                $key['time'] = date('Y-m-d H:i', $key['time']);
                // 计算消息长度
                $key['views'] = strlen($key['msg']);

                // 处理图标图片
                $key['icon_img'] = cdnurl($key['icon_image'], true);

                // 处理用户信息
                $userIds = explode(',', $key['userids']);
                $useimg = [];
                foreach ($userIds as $userId) {
                    if (!isset($userCache[$userId])) {
                        $userCache[$userId] = Db::name('user')->where('id', $userId)->find();
                    }
                    $user = $userCache[$userId];

                    if (!isset($logCache[$key['id']][$userId])) {
                        $logCache[$key['id']][$userId] = Db::name('aa_note_log')->where([
                            'nid' => $key['id'],
                            'uid' => $userId
                        ])->find();
                    }
                    $see = $logCache[$key['id']][$userId];

                    if ($user){
                        $userInfo = [
                            'see' => $see ? 1 : '',
                            'avatar' => $user['avatar']
                        ];
                    }else{
                        $userInfo = [
                            'see' => '',
                            'avatar' => ''
                        ];
                    }

                    $useimg[] = $userInfo;
                }

                $key['user_img'] = $useimg;
                $pull = count($useimg) - 6;
                $key['user_more'] = count($useimg) > 6 ? ' + ' . $pull : '';
            }

            // 返回成功响应
            $this->success('所有的信息!', $lists);

    }

 /**
 * 记一笔详情
 *
 * @return void
 */
public function getinfobyid()
{
    // 获取请求参数中的笔记 ID
    $id = $this->request->param('id');
    // 获取当前用户的 ID
    $uid = $this->auth->id;

        // 查询笔记信息
        $info = Db::name('aa_note')->where(['id' => $id])->find();

        // 检查笔记是否存在
        if (!$info) {
            $this->error('笔记不存在');
            return;
        }

        // 如果当前用户是笔记的创建者，更新消息状态为已读
        if ($uid == $info['user_id']) {
            Db::name('aa_message')
                ->where(['user_id' => $uid])
                ->where(['note_id' => $id])
                ->update(['status' => 1]);
        }

        // 检查用户是否已经查看过该笔记
        $log = Db::name('aa_note_log')->where(['nid' => $id, 'uid' => $uid])->find();
        // 查询当前用户信息
        $me = Db::name('user')->where(['id' => $uid])->find();

        // 如果用户未查看过该笔记，添加查看记录
        if (!$log) {
            Db::name('aa_note_log')->insert([
                'uname' => $me['nickname'] . '已阅读信息',
                'nid' => $id,
                'uid' => $uid,
                'time' => date('Y-m-d H:i')
            ]);
        }

        // 查询笔记创建者的信息
        $user = Db::name('user')->where(['id' => $info['user_id']])->find();

        // 处理笔记中的图片信息，将图片字符串按逗号分割成数组
        $info['images'] = explode(',', $info['images']);
        // 添加笔记创建者的头像信息
        $info['avatar'] = $user['avatar'];
        // 添加笔记创建者的昵称信息，格式为 "类型:昵称"
        $info['user_nickname'] = $user['types'] . ':' . $user['nickname'];

        // 查询笔记的查看记录
        $logs = Db::name('aa_note_log')->where(['nid' => $id])->select();
        // 将查看记录添加到笔记信息中
        $info['logs'] = $logs;

        // 添加一个消息提醒
        $msg = [
            'user_id' => $info['user_id'],
            'note_id' => $id
        ];
        Db::name('aa_message')->insert($msg);

        // 返回成功响应，包含笔记详情信息
        $this->success('记一笔详情!', $info);

}

    /*
     * 回复信息
     * */

    public function getbackbyid(){

        $id=$this->request->param('id');
        
        
            
//        $uid=$this->auth->id;

        $uid=$this->auth->id;
        $info=Db::name('aa_note')
            ->where(['id'=>$id])
            ->find();
        $list=Db::name('aa_note_back')->where(['note_id'=>$id])->select();


        foreach ($list as &$key){

            $key['images']=explode(',',$key['images']);

        }

        $this->success('回复信息!',$list);
    }



    /**
     * 回复消息
     */

    public function submitsbackmsg(){

        $images=$this->request->param('image');
        $usermsg=$this->request->param('usermsg');
        $id=$this->request->param('id');
        $uid=$this->auth->id;

        $user=Db::name('user')->where(['id'=>$uid])->find();


        $data['usermsg']=$usermsg;
        $data['note_id']=$id;
        $data['user_id']=$uid;


        foreach ($data as $key=>$v){
            if (!$v){
                $this->error('请填写完整信息!');
            }
        }

        $data['images']=$images;

        $data['times']=date('Y-m-d H:i');
        $data['user_avatar']=$user['avatar'];
        $data['user_nickname']=$user['types'].':'.$user['nickname'];

        Db::name('aa_note_back')->data($data)->insert();


        $data['user_nickname']=$user['types'].':'.$user['nickname'];

        $note=Db::name('aa_note')->where(['id'=>$id])->find();

//添加一个消息提醒
        $msg['user_id']=$note['user_id'];
        $msg['note_id']=$id;
        Db::name('aa_message')->data($msg)->insert();


        $this->success('回复消息成功!');



    }



    /*所有的信息*/
    public function getallnotes(){


        $uid=$this->auth->id;
        $data=$this->request->param();

        $map[]=['user_id','eq',$uid];

        if ($data['order_id']){
            $map[]=['orders_id','eq',$data['order_id']];
        }

        if ($data['icons_id']){
            $map[]=['icon_id','eq',$data['icons_id']];
        }

        if ($data['merch_id']){
            $map[]=['merch_id','eq',$data['merch_id']];
        }

        if ($data['users_id']){
            $map[]=['user_id','eq',$data['users_id']];
        }

        if ($data['status_id']==1){
            $map[]=['status','eq',$data['status_id']];
        }
        if ($data['status_id']==0){
            $map[]=['status','eq',$data['status_id']];
        }


        $lists=  Db::name('aa_note')
            ->where($map)
            ->order('id  desc')
            ->select();

        $ret=Db::getLastSql();


        foreach ($lists as &$key){

            $key['time']=date('Y-m-d  H:i',$key['time']);
            $key['views']=strlen($key['msg']);


            $case=Db::name('aa_case')->where(['id'=>$key['orders_id']])->find();
            if ($case){
                $key['order_title']=$case['order'];
            }else{
                $key['order_title']='';
            }



            $icons=Db::name('aa_icons')->where(['id'=>$key['icon_id']])->find();

            $key['icon_title']=$icons['name'];
            $key['icon_img']=cdnurl($icons['image'],true);


            $users=Db::name('user')->where('id','in',$key['userids'])->select();

            $useimg=[];

            foreach ($users as &$ke){


                $see=Db::name('aa_note_log')->where(['nid'=>$key['id'],'uid'=>$ke['id']])->find();

                $user['see']=$see?1:'';
                $user['avatar']=$ke['avatar'];
                $useimg[]=$user;

            }


            $key['user_img']=$useimg;

            $pull=count($useimg)-6;

            $key['user_more']=count($useimg)>6?'+'.$pull:'';

        }


        $this->success('所有的信息!',$lists);


    }


    /**
     * 设置为开
     */

    public function setnoteopen(){

        $id=$this->request->param('id');

        Db::name('aa_note')->where(['id'=>$id])->update(['status'=>1]);

        $uid=$this->auth->id;
        $me=Db::name('user')->where(['id'=>$uid])->find();

        Db::name('aa_note_log')
            ->data(['uname'=>$me['nickname'].'已设置为完成','nid'=>$id,'uid'=>$uid,'time'=>date('Y-m-d h:i')])->insert();



        $this->success('所有的信息!');

    }

    //删除信息
    public function deletenote(){

        $id=$this->request->param('id');
        $uid=$this->auth->id;
        $info=Db::name('aa_note')->where(['id'=>$id,'user_id'=>$uid])->find();
        if (!$info){
            $this->error('不是您发布的,无法删除!');
        }
        Db::name('aa_note')->where(['id'=>$id])->delete();
        $this->success('所有的信息!');

    }


}